using System;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

namespace DanielSig
{
	public static class XArray
	{
		public static LinkedList<T> ToLinkedList<T>(this T[] arr)
		{
			LinkedList<T> list = new LinkedList<T>();
			foreach(T item in arr)
			{
				list.AddLast(item);
			}
			return list;
		}
		public static SortedLinkedList<T> ToSortedLinkedList<T>(this T[] arr)
		{
			SortedLinkedList<T> list = new SortedLinkedList<T>();
			foreach(T item in arr)
			{
				list.Add(item);
			}
			return list;
		}
		public static String ToArrayString<T>(this T[] arr, Func<T, String> predicate)
		{
			return arr.ToArrayString(predicate, ",", "[", "]");
		}
		public static String ToArrayString<T>(this T[] arr, Func<T, String> predicate, String separator)
		{
			return arr.ToArrayString(predicate, separator, "[", "]");
		}
		public static String ToArrayString<T>(this T[] arr, Func<T, String> predicate, String separator, String start, String end)
		{
			if(arr != null)
			{
				StringBuilder builder = new StringBuilder(start, arr.Length * 5);
				foreach (T item in arr)
				{
					builder.Append((predicate(item) ?? "null") + separator);
				}
				if(builder.Length > separator.Length)
				{
					builder.Length -= separator.Length;
				}
				builder.Append(end);
				return builder.ToString();
			}
			return "null";
		}
		public static String ToArrayString<T>(this T[] arr)
		{
			return arr.ToArrayString(",", "[", "]");
		}
		public static String ToArrayString<T>(this T[] arr, String separator)
		{
			return arr.ToArrayString(separator, "[", "]");
		}
		public static String ToArrayString<T>(this T[] arr, String separator, String start, String end)
		{
			return arr.ToArrayString(x => x == null ? "null" : x.ToString(), separator, start, end);
		}
		public static int IndexOf<T>(this T[] arr, T element)
		{
			for(int i = 0; i < arr.Length; i++)
				if(arr[i].Equals(element)) return i;
			return -1;
		}
		public static int LastIndexOf<T>(this T[] arr, T element)
		{
			int i = arr.Length;
			while(i-- > 0)
				if(arr[i].Equals(element)) return i;
			return -1;
		}
		public static int IndexOf<T>(this T[] arr, Func<T, bool> predicate)
		{
			for(int i = 0; i < arr.Length; i++)
				if(predicate(arr[i])) return i;
			return -1;
		}
		public static int LastIndexOf<T>(this T[] arr, Func<T, bool> predicate)
		{
			int i = arr.Length;
			while(i-- > 0)
				if(predicate(arr[i])) return i;
			return -1;
		}
		public static T[] SetEach<T>(this T[] arr, Func<T, int, T> setter)
		{
			for(int i = 0; i < arr.Length; i++)
				arr[i] = setter(arr[i], i);
			return arr;
		}
	}
}